<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2017/8/18
 * Time: 15:55
 */

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Category extends Controller
{
    private $category;

    /**
     * Category constructor.
     * @param $category
     */
    public function __construct()
    {
        parent::__construct();
        $this->category = new \app\admin\model\Category();
    }


    public function index()
    {
        $all = \app\admin\model\Category::all();
        $this->view->assign("category", $all);
        return $this->fetch("index");
    }

    public function add()
    {
        if (Request::instance()->has("submit")) {
            $category = $this->category;
            $category->name = input("post.name");
            //重复检查
            $all = $category->where("name", $category->name)
                ->find();
            if ($all) {//重复
                return $this->error("已有该内容");
            } else {
                if ($category->save()) {
                    return $this->success("添加成功");
                } else {
                    return $this->error("添加失败，请稍后重试");
                }
            }
        } else {
            return $this->fetch("add");
        }
    }

    public function remove()
    {
        if (Request::instance()->has("id")) {
            $id = input("get.id");
            $result = \app\admin\model\Category::destroy($id);
            if ($result) {
                return $this->success("删除成功");
            } else {
                return $this->error("删除失败");
            }
        }

    }
}